/*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2011.
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Telemetry file stream.

-------------------------------------------------------------------------
History:
- 12:05:2011: Created by Paul Slinger

*************************************************************************/

#include "StdAfx.h"

#if !defined(CAFE) && defined(USE_TELEMETRY)
#include "TelemetryFileStream.h"

namespace Telemetry
{
	const string CFileStream::ms_defaultDir("%USER%/Telemetry/"), CFileStream::ms_defaultExtension("tlm");

	CFileStream::CFileStream() : m_pFile(NULL)
	{
	}

	CFileStream::~CFileStream()
	{
		Shutdown();
	}

	bool CFileStream::Init(const string &fileName)
	{
		string	formattedFileName = fileName;

		FormatFileName(formattedFileName);

		m_pFile = gEnv->pCryPak->FOpen(formattedFileName.c_str(), "wb");

		return m_pFile != NULL;
	}

	void CFileStream::Shutdown()
	{
		if(m_pFile)
		{
			gEnv->pCryPak->FClose(m_pFile);

			m_pFile = NULL;
		}
	}

	void CFileStream::Release()
	{
		delete this;
	}

	void CFileStream::Write(const uint8 *pData, size_t size)
	{
		CRY_ASSERT(pData);

		CRY_ASSERT(size);

		if(m_pFile)
		{
			gEnv->pCryPak->FWrite(pData, size, m_pFile);

			gEnv->pCryPak->FFlush(m_pFile);
		}
	}

	void CFileStream::FormatFileName(string &fileName) const
	{
		size_t	pos = fileName.find("\\/");

		if(pos == string::npos)
		{
			gEnv->pCryPak->MakeDir(ms_defaultDir.c_str());

			fileName.insert(0, ms_defaultDir);
		}

		pos = fileName.find_last_of(".");

		fileName.insert(pos, GetTimeStamp());

		if(pos == string::npos)
		{
			fileName.append(".");

			fileName.append(ms_defaultExtension);
		}
	}

	string CFileStream::GetTimeStamp() const
	{
		time_t	currentTime;

		time(&currentTime);

		char	timeStamp[256];

		strftime(timeStamp, 20, "_%y-%m-%d_%H-%M-%S", localtime(&currentTime));

		return string(timeStamp);
	}
}

#endif
